<?php
declare (strict_types = 1);

namespace app\auth\controller;

use app\auth\BaseController;
use app\auth\common\util\ApiUtil;
use app\auth\model\RightModel;
use app\auth\model\RoleRightLinkModel;
use app\auth\service\DeptService;
use app\auth\service\RightService;
use app\auth\service\RoleService;
use think\facade\Db;
use think\facade\Validate;

class RoleController extends BaseController
{

    public function __construct(RoleService $roleService,DeptService $deptService,RightService $rightService)
    {
        $this->roleService = $roleService;
        $this->deptService = $deptService;
        $this->rightService = $rightService;
    }

    public function list()
    {
        $params = request()->param();
        $where = $limit = $whereIn = array();
        $limit['page'] = !empty($params['page'])?intval($params['page']):1;
        $limit['pagesize'] = !empty($params['pagesize'])?intval($params['pagesize']):10;
        $name = $params['name']??null;
        if(!empty($name)) $where[] = ['name','like', '%'.$name.'%'];
        $type = $params['type']??null;
        if(!empty($type)) $where[] = ['type','=', $type];
        $range = $params['range']??null;
        if(!empty($range)) $where[] = ['range','=', $range];
        $dept_ids = $params['dept_ids']??null;
        if(!empty($dept_ids)){
            $whereIn[0] = 'dept_id';
            $whereIn[1] = explode(',', $dept_ids);
        }
        $total = $this->roleService->count($where,$whereIn);
        $list = $this->roleService->list($where , $limit,[],$whereIn);
        return ApiUtil::normal(['total'=>$total,'list'=>$list]);
    }

    /**
     * 创建角色.
     */
    public function add(RightModel $rightModel,RoleRightLinkModel $roleRightLinkModel)
    {
        $model = $this->roleService->model();
        $params = request()->param();
        $validate = Validate::rule([
            'name'=>'require|unique:'.$model->getTable(),
            'dept_id' => 'require',
            'status' => 'require',
            'type' => 'require',
            'range' => 'require',
        ]);
        if(!$validate->check($params)) return ApiUtil::normal(null, $validate->getError(), ApiUtil::CODE_FAIL);
        if(!$this->deptService->count(['id'=>$params['dept_id']])) return ApiUtil::normal(null, '不存在部门', ApiUtil::CODE_FAIL);
        if($rightModel::whereIn('id', $params['right_ids'])->count()!=count($params['right_ids'])) return ApiUtil::normal(null, '勿选择不存在的权限', ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            $data =  array();
            $data['dept_id'] = $params['dept_id'];
            $data['name'] = $params['name'];
            $data['status'] = $params['status'];
            $data['type'] = $params['type'];
            $data['range'] = $params['range'];
            $data['deadline'] = 0;
            $data['createtime'] = time();
            $lastId = $this->roleService->insertGetId($data);
            empty($lastId) && ApiUtil::abort('创建角色失败');
            //关联角色和权限
            //将pid不为0的权限关联起来
            $p_rights = $rightModel->where('pid', 0)->field(['id','pid'])->select()->column('id');
            $right_role_link_list = [];
            foreach ($params['right_ids'] as $right_id){
                if (!in_array($right_id, $p_rights)){
                    $right_role_link_list[] = [
                        'right_id' => intval($right_id),
                        'role_id' => intval($lastId)
                    ];
                }
            }
            if ($right_role_link_list){
                !$roleRightLinkModel->insertAll($right_role_link_list) && ApiUtil::abort('关联权限失败');
            }
            DB::commit();
            return ApiUtil::normal( ['id'=>$lastId]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    public function update(RightModel $rightModel,RoleRightLinkModel $roleRightLinkModel){
        $params = request()->param();
        $model = $this->roleService->model();
        $validate = Validate::rule([
            'id'=>'require',
            'name'=>'require|unique:'.$model->getTable().',name,'.$params['id'],
            'dept_id' => 'require',
            'status' => 'require',
            'type' => 'require',
            'range' => 'require',
            'right_ids' => 'require',
        ]);
        if(!$validate->check($params)) return ApiUtil::normal(null, $validate->getError(), ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            //数据库数据校验
            if(!$this->deptService->count(['id'=>$params['dept_id']])) ApiUtil::abort( '不存在部门');
            $rightModel::where(['name'=>$params['name']])->whereNotIn('id', [$params['id']])->count() && ApiUtil::abort( '已存在角色名称');
            $rightModel::whereIn('id', $params['right_ids'])->count()!=count($params['right_ids']) && ApiUtil::abort( '勿选择不存在的权限');
            $data =  array();
            $data['dept_id'] = $params['dept_id'];
            $data['name'] = $params['name'];
            $data['status'] = $params['status'];
            $data['type'] = $params['type'];
            $data['range'] = $params['range'];
            $update = $this->roleService->update(['id'=>$params['id']],$data);
            if(empty($update) && $update!=0) ApiUtil::abort('修改角色失败');
            //关联角色和权限
            //删除数据库中旧的关联
            if(!$roleRightLinkModel::where('role_id', $params['id'])->delete()) ApiUtil::abort( '删除旧权限关联失败');
            //将pid不为0的权限关联起来
            $p_rights = $rightModel->where('pid', 0)->field(['id','pid'])->select()->column('id');
            $right_role_link_list = [];
            foreach ($params['right_ids'] as $right_id)
                if (!in_array($right_id, $p_rights)){
                    $right_role_link_list[] = [
                        'right_id' => $right_id,
                        'role_id' => $params['id']
                    ];
                }
            if ($right_role_link_list){
                !$roleRightLinkModel->insertAll($right_role_link_list) && ApiUtil::abort( '关联权限失败');
            }
            DB::commit();
            return ApiUtil::normal( ['id'=>$params['id']]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    public function delete(RoleRightLinkModel $roleRightLinkModel){
        $ids = input('ids',[]);
        if (empty($ids)) return ApiUtil::normal(null, "请传入要删除的角色ID", ApiUtil::CODE_FAIL);
        DB::startTrans();
        try{
            $roleRightLinkModel::whereIn('role_id', $ids)->delete();
            $del = $this->roleService->delete(['id',$ids]);
            if(!$del) ApiUtil::abort( "删除失败");
            DB::commit();
            return ApiUtil::normal(['id'=>$ids]);
        }catch (\Exception $e){
            DB::rollBack();
            return ApiUtil::excep($e);
        }
    }

    // 筛选配置
    public function opt(){
        //部门选项
        $dept_list = $this->deptService->list();
        //角色类型
        $type_list = $this->roleService->model()::$TYPE_STR;
        //角色状态
        $status_list = $this->roleService->model()::$STATUS_STR;
        //获取权限表
        $right_tree = $this->rightService->rightTree();
        return ApiUtil::normal([
            'dept_list' => $dept_list,
            'type_list' => $type_list,
            'status_list' => $status_list,
            'right_tree' => $right_tree,
            'range_obj' => $this->roleService->model()::$RANGE_STR,
        ]);
    }
}
